package cn.com.tianpeidong.restaurantadmin.project.admin.dishestype.service.impl;

import cn.com.tianpeidong.restaurantadmin.common.exception.BusinessException;
import cn.com.tianpeidong.restaurantadmin.common.util.msg.MessageUtils;
import cn.com.tianpeidong.restaurantadmin.project.admin.dishes.mapper.DishesMapper;
import cn.com.tianpeidong.restaurantadmin.project.admin.dishestype.entity.DishesType;
import cn.com.tianpeidong.restaurantadmin.project.admin.dishestype.mapper.DishesTypeMapper;
import cn.com.tianpeidong.restaurantadmin.project.admin.dishestype.service.IDishesTypeService;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author tianpeidong
 * @version 创建时间: 19-3-26 下午9:44
 */
@Service
public class DishesTypeServiceImpl implements IDishesTypeService {

    @Autowired
    private DishesTypeMapper dishesTypeMapper;

    @Autowired
    private DishesMapper dishesMapper;

    @Override
    public List<DishesType> listDishesType(DishesType dishesTypeVo) {
        return dishesTypeMapper.listDishesType(dishesTypeVo);
    }

    @Override
    public DishesType addDishesType(@NonNull DishesType dishesType) {
        DishesType dbData = dishesTypeMapper.getByTypeName(dishesType.getTypeName());
        if (dbData != null) {
            throw new BusinessException(MessageUtils.message("dishesType.exist"));
        }
        dishesTypeMapper.insert(dishesType);
        return dishesType;
    }

    @Override
    public DishesType editDishesType(@NonNull DishesType dishesType) {
        DishesType dbData = dishesTypeMapper.getById(dishesType.getId());
        if (dbData == null) {
            throw new BusinessException(MessageUtils.message("dishesType.not.exist"));
        }
        DishesType dishesTypeExist = dishesTypeMapper.getByTypeName(dishesType.getTypeName());
        if (dishesTypeExist != null && ! dishesTypeExist.getId().equals(dishesType.getId())) {
            throw new BusinessException(MessageUtils.message("dishesType.exist"));
        }
        dishesTypeMapper.update(dishesType);
        return dishesType;
    }

    @Override
    public void deleteDishesType(@NonNull Long id) {
        int count = dishesMapper.checkDishesTypeUnderUse(id);
        if (count > 0) {
            throw new BusinessException(MessageUtils.message("dishesType.under.use"));
        }
        dishesTypeMapper.deleteById(id);
    }

    @Override
    public DishesType getDishesTypeById(@NonNull Long id) {
        return dishesTypeMapper.getById(id);
    }

}
